#!/usr/bin/env python
# -*- coding: utf-8 -*-

import tornado
import tornado.web
import datetime
from utils import log
import json
from config import etc
from controls import data_journey_base_mysql
from controls import data_journey_info_mysql
from controls import data_journey_image_mysql
from controls import data_journey_mark_mysql
from controls import data_img_base_mysql
from utils import fdfs
from utils import file_util
from utils.session_base import ApiGuest
from utils.session_mc import BaseHandler

class PublishHandler( BaseHandler ) :

    @ApiGuest
    def post( self ) :
        userid = self.ss_params['userid']
        cityid = self.ss_params['cityid']
        journeyid = self.ss_params['journeyid']
        title = self.ss_params['title']
        
        # files info
        files_dict = {}
        if ( self.request.headers["Content-Type"].startswith('multipart/form-data')) :
            file_metas = self.request.files['imgfile']
            for meta in file_metas :
                raw_name = meta['filename']
                log.i(raw_name)
                files_dict[raw_name] = meta

        # journey detail
        journey = self.ss_params['journey']
        log.i( 'userid=%s, cityid=%s, journeyid=%s, title=%s, journey=%s' % (userid, cityid, journeyid, title, journey) )
        if not ( userid and journeyid and cityid and journey) : 
            log.w('params fetching error')
            res = { 'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{} }
            self.write( json.dumps(res) )
            self.finish()
            return

        cur_time = datetime.datetime.now()
        # result
        res = { 'idx':self.ss_idx, 'ret':0, 'msg': 'ok', 
                'res':{'userid':userid, 'cityid':cityid, 'journeyid':journeyid, 'title':title,
                        'utime':cur_time.strftime("%Y-%m-%d %H:%M:%S"), 'journey':journey} }

        try : 
            delete_journey_all_by_cityid_userid ( cityid, userid )
            
            base_item = {}
            base_item['userid'] = userid
            base_item['journeyid'] = journeyid
            base_item['title'] = title
            base_item['utime'] = cur_time
            log.i( 'base_item : %s' % base_item )

            # insert into journey_base
            data_journey_base_mysql.add_journey_base_item( cityid, base_item )

            for journey_item in journey :
                markid = journey_item['markid']
                info_item = {}
                info_item['userid'] = userid
                info_item['journeyid'] = journeyid
                info_item['markid'] = markid
                info_item['sightid'] = journey_item['sightid']
                info_item['ordernum'] = journey_item['order']

                mark_item = {}
                mark_item['userid'] = userid
                mark_item['markid'] = markid
                mark_item['mark'] = journey_item['mark']
                mark_item['ctime'] = journey_item['ctime'] if journey_item['ctime'] else cur_time
    
                log.i( 'mark_item : %s' % mark_item )
                log.i( 'info_item : %s' % info_item )        

                data_journey_info_mysql.add_journey_info_item( cityid, info_item )
                data_journey_mark_mysql.add_journey_mark_item( cityid, mark_item )

                image_item = {}
                image_item['userid'] = userid
                image_item['markid'] = markid
                
                #save_journey_res = res['res']['journey']
                #save_journey_res[journey_item['order']] = {'markid': markid, 'sightid': journey_item['sightid']}

                for images in journey_item['image'] : 

                    # get raw filename
                    raw_filename = images['imgname'] if images['imgname'].endswith('.jpg') else images['imgname']+ '.jpg'
                    ctime = images['ctime']
                    if raw_filename not in files_dict :
                        images['imgname'] = raw_filename
                        images['imgid'] = ''
                        images['imgurl'] = ''
                        continue
                    log.i("update file to fdfs: " + raw_filename)
                    file = files_dict[raw_filename]
                    file_res = file_util.img_file_upload(file)
                    # if img file save success
                    if file_res and file_res['ret'] == 0 :

                        image_item['imgid'] = file_res['res']['imgid']
                        image_item['imgname'] = raw_filename
                        image_item['ctime'] = ctime if ctime else cur_time.strftime("%Y-%m-%d %H:%M:%S")

                        log.i( 'image_item : %s' % image_item )
                        data_journey_image_mysql.add_journey_image_item( cityid, image_item )
                        
                        images['imgname'] = raw_filename
                        images['imgid'] = file_res['res']['imgid']
                        images['imgurl'] = 'http://static.shitouren.com/group' + str(file_res['res']['group'])+'/'+str(file_res['res']['path'])+'.'+str(file_res['res']['ext'])

            #log.i('publish')

            log.i(res)
            self.write( json.dumps(res) )
            self.finish()
            return
        except Exception as e :
            log.exp(e)
            res = {'op':False, 'msg':'操作超时，请重新发布。'}
            self.write( json.dumps(res) )
            self.finish()
            return


def delete_journey_all_by_cityid_userid(p_cityid, p_userid):
    try : 
        data_journey_base_mysql.delete_journey_by_userid( int(p_cityid) , int(p_userid) )
        data_journey_info_mysql.delete_journey_info_by_userid( int(p_cityid) , int(p_userid) )
        data_journey_mark_mysql.delete_journey_mark_by_userid( int(p_cityid) , int(p_userid) )
        # get all journey imgids
        imgid_list = data_journey_image_mysql.get_journey_imgid_list_by_userid( int(p_cityid) , int(p_userid) )
        url_list = []
        if imgid_list :
            url_list = data_img_base_mysql.get_img_url_by_imgid_list( imgid_list )
        for imgurl in url_list :
            if not imgurl : continue
            index = imgurl.find('group')
            imgurl = imgurl[index:]
            index = imgurl.find('/')
            # get groupid
            p_group = imgurl[5:index]
            file_id = imgurl[index +1 :]

            file_id_100 = file_id[ 0:-4 ] + '_100' + file_id[ -4: ]
            file_id_300 = file_id[ 0:-4 ] + '_300' + file_id[ -4: ]

            fdfs.delete_file_by_group_file_id( p_group, file_id )
            fdfs.delete_file_by_group_file_id( p_group, file_id_100 )
            fdfs.delete_file_by_group_file_id( p_group, file_id_300 )
    
        if imgid_list :
            data_img_base_mysql.delete_img_base_by_imgid_list( imgid_list )
        data_journey_image_mysql.delete_journey_img_by_userid( int(p_cityid) , int(p_userid) )
        return True
    except Exception as e :
        log.exp(e)
        return False
    

class ApiNotFoundHandler( BaseHandler ) : 
    def get( self ) :
        raise toenado.web.HTTPError( 503 )
    @tornado.web.asynchronous
    def post( self ) :
        log.i( '503')
        res = { 'idx':-1, 'ret':-5, 'msg':etc.err_no_api, 'res':{} }
        self.write( json.dumps(res) )
        self.finish()
